const { Controller } = require('egg');

class ChatController extends Controller {
  async index() {
    const { ctx, app } = this;
    if (!ctx.websocket) {
      throw new Error('this function can only be use in websocket router');
    }

    console.log('client connected');

    ctx.websocket
      .on('message', (msg) => {
        console.log('[api] receive', msg);

        ctx.websocket.send(JSON.stringify({
          type: 'reply',
          content: `Server received: ${msg}`
        }));
      })
      .on('close', (code, reason) => {
        console.log('websocket closed', code, reason);
      });
  }
}

module.exports = ChatController;
